package com.znh.main;

import com.znh.common.Utils;
import com.znh.entity.Comment;
import com.znh.entity.GameRule;
import com.znh.entity.Manual;
import com.znh.entity.Memo;
import com.znh.enums.PieceInitLocationEnum;
import com.znh.enums.PiecePlayerEnum;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Map;


public class MainFrame extends JFrame implements ActionListener {
    /**
     * 棋盘面板
     */
    GamePanel gamePanel;
    /**
     * 按钮面板
     */
    JPanel btnArea;
    /**
     * 注释面板
     */
    JPanel noteArea;
    /**
     * ‘前进’分叉区域
     */
    static JPanel forkArea;
    /**
     * 悔棋按钮
     */
    private static JButton btn_regret;
    /**
     * 前进按钮
     */
    private static JButton btn_forward;
    /**
     * 翻转按钮
     */
    private static JButton btn_reserve;
    /**
     * 提示标签
     */
    private static JLabel label_tip;
    /**
     * 评论区
     */
    public static JTextArea comment;
    /**
     * 存储分叉按钮集合
     */
    private static ArrayList<JButton> forkBtnList= new ArrayList<JButton>();


    MainFrame() throws Exception {
        //创建窗口
        JFrame frame = new JFrame();
        frame.setResizable(false);  //窗口不可调节
        frame.setSize(500, 650);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());    //边框布局
        //棋盘区域
        gamePanel = new GamePanel();
        frame.add(gamePanel, BorderLayout.CENTER);
        //按钮区域
        btnArea = new JPanel();
        btnArea.setPreferredSize(new Dimension(130, 450));
        frame.add(btnArea, BorderLayout.EAST);
        //提示标签
        label_tip = new JLabel();
        label_tip.setBorder(BorderFactory.createBevelBorder(1));
        label_tip.setFont(new Font("宋体", Font.BOLD, 15));
        label_tip.setHorizontalAlignment(SwingConstants.CENTER);
        label_tip.setPreferredSize(new Dimension(120, 50));
        label_tip.setText(GameRule.CUR_ROUND == PiecePlayerEnum.RED ? "红方走" : "黑方走");
        btnArea.add(label_tip);
        //保存棋谱按钮
        JButton btn_saveManual = new JButton("保存棋谱");
        btn_saveManual.setPreferredSize(new Dimension(120, 50));
        btn_saveManual.setFont(new Font("宋体", Font.CENTER_BASELINE, 15));
        btn_saveManual.setFocusPainted(false);
        btn_saveManual.addActionListener(this);
        btnArea.add(btn_saveManual);
        //导入棋谱按钮
        JButton btn_importManual = new JButton("导入棋谱");
        btn_importManual.setPreferredSize(new Dimension(120, 50));
        btn_importManual.setFont(new Font("宋体", Font.CENTER_BASELINE, 15));
        btn_importManual.setFocusPainted(false);
        btn_importManual.addActionListener(this);
        btnArea.add(btn_importManual);
        //悔棋按钮
        btn_regret = new JButton("悔棋");
        btn_regret.setPreferredSize(new Dimension(120, 50));
        btn_regret.setFont(new Font("宋体", Font.CENTER_BASELINE, 15));
        btn_regret.setFocusPainted(false);
        btnArea.add(btn_regret);
        btn_regret.addActionListener(this);
        //前进按钮
        btn_forward = new JButton("前进");
        btn_forward.setPreferredSize(new Dimension(120, 50));
        btn_forward.setFont(new Font("宋体", Font.CENTER_BASELINE, 15));
        btn_forward.setFocusPainted(false);
        btnArea.add(btn_forward);
        btn_forward.addActionListener(this);
        btn_regretForward_setEnable();
        //翻转按钮
        btn_reserve = new JButton("翻转");
        btn_reserve.setPreferredSize(new Dimension(120, 50));
        btn_reserve.setFont(new Font("宋体", Font.CENTER_BASELINE, 15));
        btn_reserve.setFocusPainted(false);
        btnArea.add(btn_reserve);
        btn_reserve.addActionListener(this);
        //分叉区域
        forkArea = new JPanel();
        forkArea.setPreferredSize(new Dimension(500, 50));
        frame.add(forkArea, BorderLayout.SOUTH);

        //注释区域
        noteArea = new JPanel();
        noteArea.setPreferredSize(new Dimension(500, 150));
        frame.add(noteArea, BorderLayout.SOUTH);
        //评论区
        comment = new JTextArea();
        comment.setLineWrap(true);//自动换行
        comment.setPreferredSize(new Dimension(450, 100));
        noteArea.add(comment);
        //评论按钮
        JButton btn_comment=new JButton("评论");
        btn_comment.setPreferredSize(new Dimension(120, 50));
        btn_comment.setFont(new Font("宋体", Font.CENTER_BASELINE, 15));
        btn_comment.setFocusPainted(false);
        noteArea.add(btn_comment);
        btn_comment.addActionListener(this);
        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        new MainFrame();
    }


    //事件监听
    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        switch (actionCommand) {
            case "导入棋谱":
                importManual();
                btn_regretForward_setEnable();
                gamePanel.repaint();
                break;
            case "保存棋谱":
                saveManual();
                break;
            case "悔棋":
                try {
                    GameRule.regret();
                    gamePanel.repaint();
                    label_tip_setText();
                    btn_regretForward_setEnable();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                break;
            case "前进":
               // gamePanel.setBtn_forward_isClick(true);
                setForkBtnList();
                createForkBtn();
                try {
                    if (forkBtnList.size()<2){
                        GameRule.forward(0);
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                } catch (ClassNotFoundException classNotFoundException) {
                    classNotFoundException.printStackTrace();
                }
                label_tip_setText();
                btn_regretForward_setEnable();
                gamePanel.repaint();
                break;
            case "翻转":
                GameRule.reverse();
                gamePanel.repaint();
                break;
            case "评论":
                submitComment();
                break;
            default:
                int index = Integer.parseInt(actionCommand)-1;
                clearForkBtn();
                try {
                    GameRule.forward(index);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                } catch (ClassNotFoundException classNotFoundException) {
                    classNotFoundException.printStackTrace();
                }
                label_tip_setText();
                btn_regretForward_setEnable();
                gamePanel.repaint();
        }
    }

    /**
     * 提示标签文字变动
     */
    public static void label_tip_setText() {
        label_tip.setText(GameRule.CUR_ROUND == PiecePlayerEnum.RED ? "红方走" : "黑方走");
    }

    /**
     * 设置‘悔棋’‘前进按钮’可用性
     */
    public static void btn_regretForward_setEnable() {
        btn_regret.setEnabled(forkBtnList.isEmpty()&&GameRule.CUR_STEP >= 0);
        ArrayList<Memo> children = GameRule.CUR_MEMO.getChildren();
        btn_forward.setEnabled(forkBtnList.isEmpty()&&children != null && !children.isEmpty());
    }

    /**
     * 保存棋谱
     */
    private void saveManual(){
        JFileChooser fileChooser=new JFileChooser();
        //只选择目录
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = fileChooser.showOpenDialog(null);
        File folder = fileChooser.getSelectedFile();
        //创建文件
        String path = folder.getAbsolutePath()+File.separator+System.currentTimeMillis()+".txt";
        File file=new File(path);
        FileOutputStream fos=null;
        ObjectOutputStream oos=null;
        if (!file.exists()){
            try {
                file.createNewFile();
                //创建文件输出流
                fos=new FileOutputStream(file);
                //创建文件对象输出流
                oos=new ObjectOutputStream(fos);
                GameRule.MANUAL.setMemo(GameRule.MEMOS);
                oos.writeObject(GameRule.MANUAL);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }finally {
                if (oos!= null){
                    try {
                        oos.close(); //oos关闭会自动关闭fos
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 导入棋谱
     */
    private void importManual(){
        JFileChooser fileChooser=new JFileChooser();
        //只选择目录
        int result = fileChooser.showOpenDialog(null);
        File file = fileChooser.getSelectedFile();
        //文件输入流
        FileInputStream fis=null;
        //文件对象输入流
        ObjectInputStream ois=null;
        try {
            fis=new FileInputStream(file);
            ois=new ObjectInputStream(fis);
            Manual manual = (Manual) ois.readObject();
            GameRule.CUR_MEMO=GameRule.MEMOS= manual.getMemo();
            Map<PiecePlayerEnum, Map<Point, String>> pointNameMap = Utils.analysisPhasePointName(manual.getInitPhase());
            //设置当前步骤指针
            GameRule.CUR_STEP=GameRule.MEMOS.getCurStep();
            //设置先手、当前回合
            GameRule.ON_THE_OFFENSIVE=GameRule.CUR_ROUND=GameRule.MEMOS.getCurRound();
            //设置红黑位置
            int redLocation = manual.getRedLocation();
            GameRule.RED_LOCATION = PieceInitLocationEnum.DOWN.ordinal()==redLocation?PieceInitLocationEnum.DOWN:PieceInitLocationEnum.UP;
            GameRule.BLACK_LOCATION=PieceInitLocationEnum.DOWN.ordinal()==redLocation?PieceInitLocationEnum.UP:PieceInitLocationEnum.DOWN;
            //初始化棋盘
            gamePanel.createPieces(pointNameMap.get(PiecePlayerEnum.RED),pointNameMap.get(PiecePlayerEnum.BLACK));
            //更新按钮、标签状态
            label_tip_setText();
            btn_regretForward_setEnable();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 提交评论
     */
    public void submitComment(){
        Comment.setComment(comment.getText());
    }

    public void setForkBtnList(){
        ArrayList<Memo> children = GameRule.CUR_MEMO.getChildren();
        if (children!=null&&children.size()>1){
            for (int i = 0; i < children.size(); i++) {
                //分叉按钮
                JButton btn_fork = new JButton(String.valueOf(i+1));
                btn_fork.setPreferredSize(new Dimension(50, 50));
                btn_fork.addActionListener(this);
                forkBtnList.add(btn_fork);
            }
        }
    }

    /**
     * 生成分叉按钮
     */
    private void createForkBtn(){
        forkBtnList.forEach(item->{
            forkArea.add(item);
        });
        forkArea.repaint();
        forkArea.revalidate();
    }

    /**
     * 清除分叉按钮
     */
    public static void clearForkBtn(){
        forkBtnList.forEach(item->{
            forkArea.remove(item);
        });
        forkBtnList.clear();
        forkArea.repaint();
        forkArea.revalidate();
    }
}
